package com.haruhi.example;


import com.haruhi.event.Message;
import com.haruhi.event.MessageQueue;
import com.haruhi.event.MessageSource;
import com.haruhi.ws.client.AbstractClientEndpoint;

import javax.websocket.CloseReason;
import javax.websocket.EndpointConfig;
import javax.websocket.Session;
import java.net.URISyntaxException;
import java.util.Map;
import java.util.concurrent.Future;

/**
 * 通过继承 AbstractClientEndpoint类 可以自定义一个客户端点
 *
 */
public class MyClientEndpoint extends AbstractClientEndpoint {

    private String data;
    /**
     * 可以自定义有构造
     * @param url
     * @param handshakeHeaders
     * @param reconnectPeriod
     * @param data
     * @throws URISyntaxException
     */
    public MyClientEndpoint(String url, Map<String,String> handshakeHeaders, long reconnectPeriod,String data) throws URISyntaxException {
        super(url, handshakeHeaders, reconnectPeriod);
        // 自己的逻辑
        this.data = data;
    }

    public MyClientEndpoint() throws URISyntaxException {
        super("", null, 1);
        // 自己的逻辑
    }

    public MyClientEndpoint(String url, Map<String,String> handshakeHeaders, long reconnectPeriod) throws URISyntaxException {
        super(url, handshakeHeaders, reconnectPeriod);
    }

    @Override
    public void onMessage(Session session, String msg) {
        // 消息只要放到这个队列 ，所有的MessageHandler接口的实现类都会收到该消息
        // 这里重写了onMessage() 你可以做其他一些处理
        MessageQueue.offer(new Message(session,msg, MessageSource.SERVER));
    }

    @Override
    public void onOpen(Session session, EndpointConfig endpointConfig) {
        System.out.println("连接成功");
        super.onOpen(session, endpointConfig);
    }

    @Override
    public void onError(Session session, Throwable throwable) {
        super.onError(session, throwable);
    }

    @Override
    public void onClose(Session session, CloseReason closeReason) {
        super.onClose(session, closeReason);
    }

    @Override
    public synchronized boolean connect(boolean autoReConnect) {
        return super.connect(autoReConnect);
    }

    @Override
    public synchronized Future<Boolean> reConnect() {
        System.out.println("开始重连");
        return super.reConnect();
    }

    @Override
    public synchronized void close() {
        super.close();
    }

}
